package com.oscar.ehome.view.setview;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.setbean.FeedBackBean;
import com.oscar.ehome.bean.setbean.TokenBean;
import com.oscar.ehome.bean.setbean.opinion.CustomConstants;
import com.oscar.ehome.bean.setbean.opinion.ImageItem;
import com.oscar.ehome.bean.setbean.opinion.IntentConstants;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.spinerpopwindow.AbstractSpinerAdapter;
import com.oscar.ehome.utils.spinerpopwindow.SpinerPopWindow;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.upload.OnUploadListener;
import com.oscar.ehome.utils.upload.UploadUtil;
import com.oscar.ehome.utils.util.AesUtils;
import com.oscar.ehome.utils.util.BitmapCompressor;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.FeedBackUtil;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.VersionUtil;
import com.oscar.ehome.utils.util.makeTime;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.pageview.NimingjubaoActivity;
import com.oscar.ehome.view.setview.adapter.QuestionAdapter;
import com.oscar.ehome.view.setview.view.FeedBackView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yanzhenjie.album.Album;

import net.tycmc.bulb.androidstandard.utils.JsonUtils;

import org.apache.commons.collections.MapUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 意见反馈
 */
public class FeedBackActivity extends BasesActivity<FeedBackView, SetPresenter> implements AbstractSpinerAdapter.IOnItemSelectListener, FeedBackView, AdapterView.OnItemClickListener,
        TextWatcher, OnUploadListener {
    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 选择问题
     */
    @BindView(R.id.btn_question)
    RelativeLayout btnQuestion;
    /**
     * 问题
     */
    @BindView(R.id.question_text)
    TextView question_text;
    /**
     * 问题描述
     */
    @BindView(R.id.question_show)
    EditText questionShow;
    /**
     * 展示图片
     */
    @BindView(R.id.grid_gridview)
    GridView gridGridview;
    /**
     * 提交按钮
     */
    @BindView(R.id.quesiton_tj)
    Button quesitonTj;
    /**
     * 剩余字数
     */
    @BindView(R.id.tvWordNumber)
    TextView tvWordNumber;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    QuestionAdapter quesAdapter;
    SetPresenter setPresenter;

    private CharSequence wordNum;//记录输入的字数
    private int selectionStart;
    private int selectionEnd;

    private volatile boolean isRunning = false;//判断线程池是否运行 标志位
    private UploadUtil mUploadUtil;

    private String sourcePath;
    private int num = 400;


    public List<String> mDataList = new ArrayList<String>();//全部图片
    public List<String> ImageList = new ArrayList<String>();//上传图片
    public List<String> keyList = new ArrayList<String>();//上传图片地址

    int i = 0;//第几张图片
    int availableSize = 0;

    //使用问题
    private List<String> nameList = new ArrayList<String>();
    SpinerPopWindow mSpinerPopWindow;
    private String uptoken;
    private String keyRand;
    private String quesadvise;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        ButterKnife.bind(this);
        setColor();
        initView();
        onClick();
    }

    @Override
    protected SetPresenter createPresenter() {
        setPresenter = new SetPresenter(this);
        return setPresenter;
    }

    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(FeedBackActivity.this).getSystemConfig().getColor()));
        TintManager.setTint(quesitonTj, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    private void initView() {
        CommonUtils.url_code = 1;
        setPresenter.getUploadToken();

        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleTopbar.setText("意见反馈");

        availableSize = 9;
        nameList.add("使用问题");
        nameList.add("功能建议");
        //初次进入
        if (question_text.getText().toString().equals("")) {
            question_text.setText("使用问题");
        }
        mSpinerPopWindow = new SpinerPopWindow(this);
        mSpinerPopWindow.refreshData(nameList, 0);
        mSpinerPopWindow.setItemListener(this);

        quesAdapter = new QuestionAdapter(this, mDataList);
        gridGridview.setAdapter(quesAdapter);

        mUploadUtil = new UploadUtil();
        mUploadUtil.setOnUploadListener(this);

    }

    private void onClick() {
        gridGridview.setOnItemClickListener(this);
        questionShow.addTextChangedListener(this);
    }

    @OnClick({R.id.title_layout_left, R.id.btn_question, R.id.question_show, R.id.quesiton_tj})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left://返回
                finish();
                break;
            case R.id.btn_question:
                showPopupMenu(btnQuestion);
                break;
            case R.id.question_show:
                break;
            case R.id.quesiton_tj://提交
                //提交反馈
                SubmitFeedBack();
                break;
        }
    }

    private void SubmitFeedBack() {
        CommonUtils.url_code = 0;
        quesadvise = "1";
        String question = question_text.getText().toString();
        if (question.equals("使用问题")) {
            quesadvise = "1";
        } else {
            quesadvise = "2";
        }
        //判断为空
        if (questionShow.length() == 0) {
            Toast.makeText(FeedBackActivity.this, "请填写问题描述", Toast.LENGTH_SHORT).show();    //弹出一个自动消失的提示框
            return;
        }

        //获取手机品牌
        String brand = Build.BRAND;
        //获取手机型号
        String model = Build.MODEL;
        //获取api版本
        String relese = Build.VERSION.RELEASE;
        String releses = VersionUtil.getVersionName(FeedBackActivity.this) + "ver" + relese;

        String token = SystemConfigFactory.getInstance(FeedBackActivity.this).getSystemConfig().getToken();
        String problemDesc = question_text.getText().toString();
        String feedbackType = quesadvise;
        String mobileSystem = brand;
        String mobileModel = model;
        String versionNo = releses;
        String imageStr = "";

        if (keyList.size() > 0) {
            imageStr = CommonUtils.ListToString(keyList, 1);
        }

        Log.d("mwh", "keyLIst" + keyList);

        setPresenter.subMitFeed(token, problemDesc, feedbackType, mobileSystem, mobileModel, versionNo, imageStr);
        showLoading();

    }

    private void showPopupMenu(RelativeLayout btnQuestion) {
        mSpinerPopWindow.setWidth(btnQuestion.getWidth());
        mSpinerPopWindow.showAsDropDown(btnQuestion);
    }

    @Override
    public void onItemClick(int postion) {
        setHero(postion);
    }

    private void setHero(int postion) {
        if (postion >= 0 && postion <= nameList.size()) {
            String value = nameList.get(postion);
            question_text.setText(value);
        }
    }

    //   获取上传到七牛图片的token值/
    @Override
    public void getUploadToken(TokenBean tokenBean) {
        uptoken = tokenBean.getUptoken();
    }

    /**
     * 反馈信息
     *
     * @param feedBackBean
     */
    @Override
    public void subMitFeed(FeedBackBean feedBackBean) {
        dismissLoading();
        ToastUtil.show(FeedBackActivity.this, feedBackBean.getMessage());
        finish();
    }

    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(FeedBackActivity.this, getString(R.string.erry));

    }

    @Override
    public void erry(String result) {
        dismissLoading();
        Toast.makeText(FeedBackActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(FeedBackActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(FeedBackActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == mDataList.size()) {
            new PopupWindows(FeedBackActivity.this, gridGridview);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        wordNum = s;//实时记录输入的字数
    }

    @Override
    public void afterTextChanged(Editable s) {
        int number = num - s.length();
        //TextView显示剩余字数
//                tvWordNumber.setText("" + number);

        selectionStart = questionShow.getSelectionStart();
        selectionEnd = questionShow.getSelectionEnd();
        if (wordNum.length() > num) {
            //删除多余输入的字（不会显示出来）
            s.delete(selectionStart - 1, selectionEnd);
            int tempSelection = selectionEnd;
            questionShow.setText(s);
            questionShow.setSelection(tempSelection);//设置光标在最后
            ToastUtil.show(FeedBackActivity.this, "本次输入以达到上限");
        }
    }

    @Override
    public void onAllSuccess() {
        isRunning = false;
        Log.d("mwh", "文件" + "全部上传成功");
    }

    @Override
    public void onAllFailed() {
        isRunning = false;
        Log.d("mwh", "文件" + "全部失败");
    }

    @Override
    public void onThreadProgressChange(int position, int percent) {
        Log.d("mwh", "文件" + position + "上传" + percent + "%");
    }

    @Override
    public void onThreadFinish(int position, String keys) {
        keyList.add(keys);
        Log.d("mwh", "文件" + position + "上传成功");
    }

    @Override
    public void onThreadInterrupted(int position) {
        Log.d("mwh", "文件" + position + "上传失败");
    }

    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            View view = View.inflate(mContext, R.layout.item_popupwindow, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);

            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Album.startAlbum(FeedBackActivity.this, 400, 9);
                    dismiss();

                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 400) {
            if (resultCode == RESULT_OK) { // 判断是否成功。
                // 拿到用户选择的图片路径List：
                mDataList = Album.parseResult(data);
                ImageList = Album.parseResult(data);
                if (mDataList.size() < 9) {
                    availableSize = availableSize - ImageList.size();
                }
                /**
                 * 上传服务器代码
                 */
                if ("".equals(uptoken)) {
                    setPresenter.getUploadToken();
                } else {
                    if (ImageList.size() > 0) {
                        startUpload();
                    }
                }
                quesAdapter.setLists(mDataList);
            }else if (resultCode == RESULT_CANCELED) { // 用户取消选择。
                // 根据需要提示用户取消了选择。
            }
        }
    }
    private void startUpload() {//模拟上传文件
        isRunning = true;
        mUploadUtil.submitAll(ImageList, uptoken);
    }
}
